﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Threading;

namespace WpfApplication3
{
    class Head
    {
        static SerialPort serialport;
        byte[] head = new byte[] { 0xAA, 0x55 };
        byte crc = 0;
        private int serportNum = 0;

        // a port megnyitásával a megadott paraméterek is beállításra kerülnek
        public bool SerialPortSet(string portname)
        {
            serialport.PortName = portname;
            serialport.Open();
            serialport.BaudRate = 19200;
            serialport.DataBits = 8;
            serialport.Parity = Parity.None;
            serialport.StopBits = StopBits.One;

            if (serialport.IsOpen)
                return true;
            else
                return false;
        }

        void Send(byte[] data)
        {
            foreach (var item in data)
            {
                crc ^= item;
            }
            byte[] outputBuffer = head.Concat(data).Concat(new byte[] { crc }).ToArray();
            // paraméterként a nulla az ofset, kiküldi soros portra az adatot
            serialport.Write(outputBuffer, 0, outputBuffer.Length);
            Thread.Sleep(250);
        }

        byte[] Receive(byte[] data)
        {
            byte[] b = new byte[serialport.BytesToRead];
            serialport.Read(b, 0, b.Length);
            return b;
        }
    }

}
